package cn.edu.jxau.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import cn.edu.jxau.service.addNotification;
import cn.itcast.commons.CommonUtils;

public class changePhotoServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
	
		/*
		 * 文件上传
		 */
		DiskFileItemFactory factory = new DiskFileItemFactory(20*1024,new File("D:/JavaApplication"));//文件的临时存储位置
		ServletFileUpload sfu = new ServletFileUpload(factory);
		sfu.setFileSizeMax(1024*1024);//设置单个文件上传的大小不超过1M
		/*sfu.setSizeMax(500*1024*1024);//设置整个表单的文件上传不超过500M*/
		try {
			@SuppressWarnings("unchecked")
			List<FileItem> list = sfu.parseRequest(request);
			System.out.println(list.size());
			FileItem fi0 =list.get(0);  //从表单中获取标题
			/*FileItem fi1 =list.get(1);  //获取图片
			FileItem fi2 =list.get(2);  //获取布局位置 
			FileItem fi3 =list.get(3);  //获取内容
*/			String title=fi0.getString("UTF-8");  
			/*String flag=fi2.getString("utf-8");
			String content=fi3.getString("utf-8");*/
			/*
			 * 得到文件的真实路径
			 */
			String root = this.getServletContext().getRealPath("/admin/picture/");
        
			String filename = fi0.getName();//获取上传文件的名称
			/*
			 * 处理文件名的绝对路径的问题 若未找到返回-1
			 */
			int index = filename.lastIndexOf("\\");
			if (index != -1) {
				filename = filename.substring(index - 1);
			}
			/*
			 * 给文件添加UUid前缀，处理文件同名问题
			 */
			String savename = CommonUtils.uuid() + "_" + filename;
			int hCode = filename.hashCode();
			String hex = Integer.toHexString(hCode);// 获得十六进制的hashCode
			/*
			 * 获取hex的前两个字母,与root连接在一起，生成一个完整的路径
			 */
			File dirFile = new File(root, hex.charAt(0) + "/" + hex.charAt(1));
			
			/*
			 * 创建目录链
			 */
			dirFile.mkdirs();
			/*
			 * 创建文件
			 */
			File destFile = new File(dirFile, savename);
			
			String realname="picture/"+hex.charAt(0) + "/" + hex.charAt(1)+"/"+savename;
			/*addNotification.pushNotification(title, realname, content, flag);*/
			// 保存文件
		  /*  fi1.write(destFile);*/		
		  
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
